package model;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

import org.bushe.swing.event.EventBus;

import constants.Events;

/**
 * A turn timer that publishes its value to the
 * EventBus on every tick.
 * TODO: Create timer interface for timers. This could be any timer,
 * not just a turn timer.
 */
public class TurnTimer {

    /**
     * aSec (a second) is 1000 milliseconds. Don't change this.
     */
    private static final int aSec = 1000;
    /**
     * Actions will be delegated to this swing timer.
     */
    private final Timer timer;
    /**
     * The timer will count down from the maxTime
     */
    private int maxTime = 10;
    /**
     * The timer's current value
     */
    private int sec = maxTime;

    /**
     * Create a turn timer
     */
    public TurnTimer(){
        timer = new Timer(0, new ActionMan());
        timer.setDelay(aSec);
    } //constructor

    /**
     * Set the maximum value this timer can count down from.
     * @param sec maximum time in seconds
     */
    public void setMaxTime(int sec){
        this.maxTime = sec;
    } //setStartTime

    /**
     * Get the maximum time.
     * @return the maximum time in seconds
     */
    public int getMaxTime(){
        return maxTime;
    } //getStartTime

    /**
     * Start ticking
     */
    public void start(){
        timer.start();
    } //start

    /**
     * Stop ticking
     */
    public void stop(){
        timer.stop();
    } //stop

    /**
     * Stops the timer, resets it and restarts it.
     */
    public void restart(){
        timer.stop();
        sec = maxTime;
        timer.restart();
    } //restart

    /**
     * This ActionListener handles the timer actions on every tick
     */
    private class ActionMan implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent arg0) {
            timer.setDelay(1000);
            if(sec == -1)
                sec = maxTime;

            EventBus.publish(Events.TIME.toString(), sec);
            if(sec == 0){
                timer.setDelay(1500);
            }
            sec--;


        } //actionPerformed
    }//ActionMan

} //end of class
